﻿
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using LuaInterface;

namespace Game
{
    public class AsyncImageDownload : MonoBehaviour
    {
        public delegate void CallBack(Sprite sprite);
        private static AsyncImageDownload _instance = null;
        public static AsyncImageDownload instance
        {
            get
            {
                if (_instance == null)
                {
                    GameObject obj = new GameObject("AsyncImageDownload");
                    _instance = obj.AddComponent<AsyncImageDownload>();
                    DontDestroyOnLoad(obj);
                    _instance.Init();
                }
                return _instance;
            }
        }

        public bool Init()
        {
            if (!Directory.Exists(Application.persistentDataPath + "/ImageCache/"))
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/ImageCache/");
            }
            return true;
        }
        public void DownLoadImageForLua(string url, LuaFunction func = null)
        {
            DownLoadImage(url, delegate (Sprite sprite)
            {
                if (func != null) func.Call(sprite);
            });
        }
        public void DownLoadImage(string url, CallBack callBack = null)
        {
            if (string.IsNullOrEmpty(url))
            {
                return;
            }
            url = url.Substring(0, url.Length - 1);
            url += "64";  //将微信大头像换成小头像
            int md5 = url.GetHashCode();
            string fileName = path + "/" + md5 + ".jpg";
            bool exist = File.Exists(fileName);

            // 如果存在  
            if (exist)
            {
                fileName = "file:///" + fileName;
            }
            else
            {
                fileName = url;
            }
            StartCoroutine(LoadLocalImage(fileName, exist, callBack));
        }
        IEnumerator LoadLocalImage(string url, bool exist, CallBack callBack = null)
        {
            Debug.Log("getting local image:" + url);
            WWW www = new WWW(url);
            yield return www;

            Texture2D texture = www.texture;
            Sprite m_sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
            if (callBack != null)
            {
                callBack(m_sprite);
            }
            if (!exist)
            {
                SaveImage(url, www.bytes);
            }
        }
        /// <summary>
        /// 将从网上下载的图片（头像）压缩成bytes保存到本地
        /// </summary>
        /// <param name="url"></param>
        /// <param name="bytes"></param>
        public void SaveImage(string url, byte[] bytes)
        {
            //用以区分图片
            int md5 = url.GetHashCode();
            string fileName = path + "/" + md5 + ".jpg";
            FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }
        public string path
        {
            get
            {
                return Application.persistentDataPath + "/ImageCache/";
            }
        }
    }
}